/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  MemberManageActivity.java   
 * @Package com.jiyi.activity.zone   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-7-20 下午2:00:51   
 * @version V1.0     
 */
package com.jiyi.activity.zone;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.zone.ZoneHaoYouBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.inteface.WebApi;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.SysUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: MemberManageActivity
 * @Description:TODO(群组成员管理)
 * @author: HYM
 * @date: 2017-7-20 下午2:00:51
 * 
 */
public class MemberManageActivity extends ActivityBase {

	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	/* activity控件 */
	@BindView(R.id.mainList)
	ListView mainList;
	@BindView(R.id.tvAllMember)
	TextView tvAllMember;
	@BindView(R.id.tvAll)
	TextView tvAll;

	// 数据适配器
	CommonAdapter<ZoneHaoYouBean> mAdapter;
	// 数据源
	List<ZoneHaoYouBean> dataList = new ArrayList<ZoneHaoYouBean>();
	// 加载进度圈
	Dialog dialog;

	// 保存当前选择的id
	ArrayList<String> idsList = new ArrayList<String>();
	boolean isDel = false;
	// 群主ID,群组ID
	String creatorId, groupId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_member_manage);
		ButterKnife.bind(this);
		init();
	}
	
	@Override
    protected void onDestroy() {
        hideDialog(dialog);
        super.onDestroy();
    }

	private void init() {
		getIntentData();
		setTop();
		setAdapter();
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-13
	 */
	private void getIntentData() {
		creatorId = getIntent().getStringExtra("creatorId");
		groupId = getIntent().getStringExtra("groupId");
		// 填充成员数据
		List<ZoneHaoYouBean> temp = new Gson().fromJson(getIntent()
				.getStringExtra("memberList"),
				new TypeToken<List<ZoneHaoYouBean>>() {
				}.getType());
		if (null != temp) {
			dataList.clear();
			dataList.addAll(temp);
		}
		tvAllMember.setText("全部成员(" + dataList.size() + ")");
		if (UserInfoUtil.getCurrentUserId() != Integer.parseInt(creatorId)) {
			tvSearch.setVisibility(View.GONE);
		}
		setCurrentNum();
	}

	private void setTop() {
		tvBack.setText("");
		tvTitle.setText("群组成员");
		tvSearch.setCompoundDrawables(null, null, null, null);
		tvSearch.setText("删除");
		tvAll.setVisibility(View.INVISIBLE);

	}

	private void setAdapter() {

		mAdapter = new CommonAdapter<ZoneHaoYouBean>(this, dataList,
				R.layout.item_haoyou_invite) {
			@Override
			public void convert(final ViewHolder holder, final ZoneHaoYouBean t) {
				holder.setOnClickListener(R.id.ivLogo, new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent(v.getContext(),
								PersonInfoActivity.class);
						intent.putExtra("id", t.getId());
						v.getContext().startActivity(intent);
					}
				});
				holder.setImage(R.id.ivLogo, t.getHead_path());
				holder.setText(R.id.tvMemberName, t.getName());
				if (isDel) {
					holder.setVisible(R.id.cbMember, true);
					holder.setChecked(R.id.cbMember, t.getIsCheck());
					holder.setOnClickListener(R.id.rlItem,
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									// 获取当前对象是否选中
									boolean isCheck = t.getIsCheck();
									// 然后设置反值
									dataList.get(holder.getPosition())
											.setIsCheck(!isCheck);
									saveIds(t.getId());
									setCurrentNum();
									// 设置checkbox选中
									holder.setChecked(R.id.cbMember,
											t.getIsCheck());
								}
							});
				} else {
					holder.setVisible(R.id.cbMember, false);
				}
			}
		};
		mainList.setAdapter(mAdapter);
		mainList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ZoneHaoYouBean zoneHaoYouBean = (ZoneHaoYouBean) parent
						.getAdapter().getItem(position);
				Intent intent = new Intent(parent.getContext(),
						PersonInfoActivity.class);
				intent.putExtra("id", zoneHaoYouBean.getId());
				parent.getContext().startActivity(intent);
			}
		});
	}

	void saveIds(String id) {
		if (!idsList.contains(id)) {
			idsList.add(id);
		} else {
			idsList.remove(id);
		}
	}

	void setCurrentNum() {
		if (idsList.size() > 0) {
			tvSearch.setText("删除(" + idsList.size() + ")");
		} else {
			tvSearch.setText("删除");
		}

		// 判断当前的选择状态
		if (!getIsAll()) {
			tvAll.setTextColor(getResources().getColor(R.color.tab_top_on));
		} else {
			tvAll.setTextColor(getResources().getColor(R.color.tab_top));
		}

	}

	/**
	 * @author: HYM
	 * @Title: allSelect
	 * @Description: TODO(全选按钮执行的方法) void
	 * @date: 2017-6-13
	 */
	void allSelect() {
		if (dataList.size() <= 0) {
			return;
		}

		boolean isAll = getIsAll();

		// 遍历全部数据，如果是需要全选则添加，如果需要反选 则删减
		for (int i = 0; i < dataList.size(); i++) {
			dataList.get(i).setIsCheck(isAll);
			if (isAll) {
				if (!idsList.contains(dataList.get(i).getId())) {
					idsList.add(dataList.get(i).getId());
				}
			} else {
				if (idsList.contains(dataList.get(i).getId())) {
					idsList.remove(dataList.get(i).getId());
				}
			}
		}
		mAdapter.notifyDataSetChanged();
		setCurrentNum();
	}

	/**
	 * @author: HYM
	 * @Title: getIsAll
	 * @Description: TODO(判断下次是否应该全选)
	 * @return boolean
	 * @date: 2017-6-13
	 */
	boolean getIsAll() {
		boolean isAll = false;

		int sel = 0;// 有选择
		int unsel = 0;// 未选择
		for (ZoneHaoYouBean haoyou : dataList) {
			if (haoyou.getIsCheck()) {
				sel++;
			} else {
				unsel++;
			}
		}
		if (sel == 0 && unsel == 0) {
			// 全部没有选择的话
			isAll = true;
		} else if (sel > 0 && unsel == 0) {
			// 子项全部选择，这时要反选
			isAll = false;
		} else if (sel == 0 && unsel > 0) {
			// 子项全部没选
			isAll = true;
		} else {
			// 子项有部分选，有部分没选的时候
			isAll = true;
		}

		return isAll;
	}

	@OnClick({ R.id.tvBack, R.id.tvSearch, R.id.tvAll })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvSearch:
			if (isDel == false) {
				tvAll.setVisibility(View.VISIBLE);
				isDel = true;
				mAdapter.notifyDataSetChanged();
				return;
			} 
			else {
				if (idsList.size() <= 0) {
					// 没有可删除成员
					tvAll.setVisibility(View.GONE);
					isDel = false;
					mAdapter.notifyDataSetChanged();
					return;
				}
			}

			for (int i = 0; i < idsList.size(); i++) {
				if (idsList.get(i).equals(creatorId)) {
					// 删除成员中包含了群主
					ToastUtil.getInstances().showMsg("不能删除群主！");
					return;
				}
			}

			doDel();
			break;
		case R.id.tvAll:
			allSelect();
			break;
		default:
			break;
		}
	}

	/**
	 * @author: HYM
	 * @Title: doDel
	 * @Description: TODO(执行删除动作) void
	 * @date: 2017-7-20
	 */
	void doDel() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", groupId);

		StringBuilder sbBuilder = new StringBuilder();
		for (int i = 0; i < idsList.size(); i++) {
			sbBuilder.append(idsList.get(i));
			sbBuilder.append(",");
		}
		
		String userList = SysUtils.SbToString(sbBuilder);

		if (!TextUtils.isEmpty(userList)) {
			params.put("str", userList);
		}

		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(this, WebApi.ZONE_GROUP_MEMBER_DEL, "",
				params, new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						if (this == null || isFinishing()) {
							return;
						}
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								Intent intent = new Intent();
								intent.putStringArrayListExtra("del_member",
										idsList);
								setResult(RESULT_OK, intent);
								finish();
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
						hideDialog(dialog);
					}
				});

	}
}
